import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Subscription } from "rxjs/Subscription";
import { CmHttp } from "CmHttp";
import { UserService } from "user";
import { SocketService } from "socket";
import { WatchlistMiniService, WatchlistGroup } from "watchlist-mini";
import { STOCK_STATUS, SummaryWithTrading, SUMMARY_STATUS } from "summary-assistant";
import { MiniAddStockComponent } from "./../../watchlist-mini/modal-addstock/mini-addstock.component";
// import { ModalAddStockComponent } from "./../../watchlist-mini/modal-addstock/modaladdstock.component";
import * as _ from "lodash";
import { OptimizeUnitPipe, DecimalPipe } from "pipes";
import { BROADCAST_TYPE, BroadcastService } from "broadcast";

let optimizeUnit = new OptimizeUnitPipe();
// console.debug("Optimize Unit: ", OptimizeUnitPipe, new OptimizeUnitPipe());

const COLOR_RED = "color-red";
const COLOR_GREEN = "color-green";
const STOPT_DETAIL = {
  amplitude: null,
  // current: null,
  pre_close: null,
  high: null,
  low: null,
  change_amount: null,
  change_rate: null,
  open: null,
  // down_price: null,
  // up_price: null,
  vol_ratio: null,
  turnover_ratio: null,
  // PE: null,
  // pb: null,
  amount_in: null,
  amount_out: null,
  balance: null,
  volume: null
};

interface FIELD_OPTION {
  withUnit?: boolean;
  withColor?: boolean;
  toFixed?: number;
  withPercent?: boolean;
}

const FIELD_LIST = {
  change_rate: {
    withPercent: true,
  },
  turnover_ratio: {
    withPercent: true,
  },
  amplitude: {
    withPercent: true,
  },
  amount_out: {
    withUnit: true,
  },
  balance: {
    withUnit: true,
  },
  volume: {
    withUnit: true,
  },
  amount_in: {
    withUnit: true
  },
  circulation_value: {
    withUnit: true
  },
  market_value: {
    withUnit: true
  },
};

const BAR_STRING = "--";

const getValueByFieldOption = (value, option: FIELD_OPTION, forceToBar = false) => {
  if (forceToBar) {
    return BAR_STRING;
  }
  let v = value;
  if (!option.withUnit && option.toFixed !== undefined) {
    v = v.toFixed(option.toFixed)
  }
  if (option.withUnit) {
    v = optimizeUnit.transform(v, undefined, undefined, option.toFixed);
  }
  if (option.withPercent) {
    return (v + "%");
  }
  return v;
};

const getFixedDetail = detail => {
  return {
    ...detail,
    current: detail.current || detail.last_px,
    high: detail.high || detail.high_px,
    low: detail.low || detail.low_px,
    change: detail.change || detail.px_change,
    change_rate: detail.change_rate || detail.px_change_rate,
    name: detail.name || detail.prod_name,
    open: detail.open || detail.open_px,
  };
};

@Component({
  selector: 'detail-basic',
  templateUrl: 'detail-basic.component.html',
  styleUrls: [
    "detail-basic.component.less"
  ],
  providers: [MiniAddStockComponent]
})
export class DetailBasicComponent implements OnInit, OnDestroy {
  @Input() placementSource; // : Observable<string>;  // "live" | "textinline" | "stock" | "vtrade";
  @Input() quoteSource: Observable<any>;
  mainSubscription: Subscription;
  placeSubscription: Subscription;
  defaultFieldOption: FIELD_OPTION = {
    withPercent: false,
    withColor: false,
    withUnit: false,
    toFixed: 2
  };
  detail = { symbol: null };
  fieldList = FIELD_LIST;
  marketStatus: string;
  // 应用的位置
  place: string;
  // 股票类型
  marketType: string;  // index, block, stock 指数,板块,个股
  // 添加自选股
  addStockSource = new ReplaySubject(1);
  // 自选股分组数量
  wlgroupLenth: number = 0;
  allWatchlistGroups: WatchlistGroup[] = [];
  currentSymbol: string;
  groupLists: WatchlistGroup[] = undefined;
  initCheckedList: string[];  // 已经包含了该自选股的分组id列表
  initUncheckedList: string[];  // 未包含该自选股的分组id列表
  actionSub = new Subject();
  actionSubscription: Subscription;

  constructor(
    private http: CmHttp,
    private socket: SocketService,
    private userService: UserService,
    private wls: WatchlistMiniService,
    private broadcast: BroadcastService
  ) { }

  ngOnInit() {
    let { quoteSource, http, socket } = this;

    if (quoteSource) {
      // console.debug("Stock Detail Subscription: ");
      this.mainSubscription = quoteSource
        .filter(stock => stock && stock.symbol)
        .subscribe((detail: SummaryWithTrading) => {
          console.debug("Detail Basic: ", detail);
          if (this.detail && this.detail.symbol) {
            socket.emit("unsub", { channel: "detail", symbols: [this.detail.symbol] });
          }
          if (detail.stockStatus === STOCK_STATUS.STOP_AND_TRADING_DAY ||
            detail.stockStatus === STOCK_STATUS.OCALL) {
            this.detail = Object.assign({}, detail, STOPT_DETAIL);
          } else {
            this.detail = getFixedDetail(detail);
          }

          this.addStockSource.next(this.detail);
          // 判断指数,板块还是个股
          if (!detail.market || detail.market.indexOf('MRI') !== -1) {
            this.marketType = "index";
          } else if (detail.market.indexOf('XBHS') !== -1) {
            this.marketType = "block";
          } else {
            this.marketType = "stock";
          }

          socket.emit("sub", { channel: "detail", symbols: [detail.symbol] })
        });
    }
    this.socket.on("detail", dynPanel => {
      // console.debug("Detail Basic: Socket:", dynPanel);
      if (this.detail.symbol == dynPanel.symbol) {
        this.detail = Object.assign({}, this.detail, dynPanel);
        this.addStockSource.next(this.detail);
      }
    });

    // 位置 "live" | "textinline" | "stock" | "vtrade";
    this.placeSubscription = this.placementSource.subscribe(place => {
      console.debug("Detail Basic place:", place);
      this.place = place;
    });
  }

  ngOnDestroy() {
    this.mainSubscription ? this.mainSubscription.unsubscribe() : null;
    this.placeSubscription ? this.placeSubscription.unsubscribe() : null;
    this.socket.emit("unsub", { channel: "detail", symbols: [this.detail.symbol] });
  }

  getColorClass(value, base) {
    if (!value || base === undefined) return "";
    return value > base ? COLOR_RED : value < base ? COLOR_GREEN : "";
  }

  getFieldToShow(key: string, value) {
    if (value === null || value === undefined) return BAR_STRING;
    if (!key || !this.fieldList[key]) {
      return getValueByFieldOption(value, this.defaultFieldOption);
    }
    return getValueByFieldOption(
      value, {
        ...this.defaultFieldOption,
        ...this.fieldList[key]
      }
    );
  }
  // 是否显示更多的详情
  isShowMore = false;
  toggleDetail(val: boolean) {
    this.isShowMore = val;
    setTimeout(_ => {
      // refresh chart
      this.broadcast.broadcast.next({
        "type": BROADCAST_TYPE.RENDER_CHAERT
      });
    }, 0);
  }
}